package internal

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/dbmodule"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"sort"

	log "github.com/sirupsen/logrus"
)

// 圣诞活动
type ChristmasActivity struct {
	activ *m.CActiv
}

func NewChristmasActivity() *ChristmasActivity {
	return &ChristmasActivity{}
}

func (this *ChristmasActivity) Init() {
	this.CheckActiv()
}

func (this *ChristmasActivity) Run(closeSig chan bool) {

}

func (this *ChristmasActivity) Destroy() {

}

func (this *ChristmasActivity) CheckActiv() {
	this.activ = m.GetCActiv(1)
	nowUnix := utils.TNow().Unix()
	if this.activ.BeginTime < nowUnix {
		this.activ = &m.CActiv{
			Uid: 1,
		}
		this.activ.Update(this.activ)
	}

	activ, err := lib.GetCurrentChristmasActivity()
	if err != nil {
		log.WithFields(log.Fields{
			"err":    err,
			"method": "ChristmasActivity.CheckActiv",
		}).Error("Christmas，没有活动，或者配表不能存在")
		return
	}

	// 活动正在经常，不需要处理
	if this.activ.ActivId == int64(activ.ActivId) {
		log.WithFields(log.Fields{
			"method": "ChristmasActivity.CheckActiv",
		}).Error("Christmas，活动正在经常，不需要处理")
		return
	}
	// 活动没有进行，需要开启活动
	uLst := make([]*m.User, 0)
	// 获取数据库中所有用户的信息
	err = dbmodule.MgoDB.GameDB.FindAll("user", nil, nil, &uLst)
	if err != nil {
		log.WithFields(log.Fields{
			"err":    err.Error(),
			"method": "ChristmasActivity.CheckActiv",
		}).Error("Christmas，查询用户失败")
		return
	}
	// 获取圣诞树的信息
	tplLst, ok := data.GetAllDatas("ChristmasTrees")
	if !ok {
		log.WithFields(log.Fields{
			"method": "ChristmasActivity.CheckActiv",
		}).Error("Christmas，没有ChristmasTrees配表，或者没有数据")
		return
	}
	// 按照圣诞树的等级排序
	sort.Slice(tplLst, func(i, j int) bool {
		valI := tplLst[i].(data.ChristmasTree)
		valJ := tplLst[j].(data.ChristmasTree)
		return valI.Id < valJ.Id
	})

	// 初始玩家的信息
	for _, item := range uLst {
		uid := item.Uid.Hex()
		uChristmasTree := m.GetUserChristmasTree(uid)
		uChristmasTree.Level = 1
		// 初始化玩家的圣诞树阈值
		for _, cItem := range tplLst {
			cItemT := cItem.(data.ChristmasTree)
			id := int64(cItemT.Id)
			ball := int64(cItemT.Ball)
			candy := int64(cItemT.Candy)
			stocking := int64(cItemT.Stocking)

			if uChristmasTree.MaxLevel < id {
				uChristmasTree.MaxLevel = id
			}

			uChristmasTree.Tree[id] = &m.ChristmasTree{
				Level:    id,
				Ball:     ball,
				Candy:    candy,
				Stocking: stocking,
			}
		}

		uChristmasTree.Update(uChristmasTree)
	}

	bTime, _ := utils.LayoutToTime(activ.BeginTime)
	eTime, _ := utils.LayoutToTime(activ.EndTime)

	this.activ.ActivId = int64(activ.ActivId)
	this.activ.BeginTime = bTime.Unix()
	this.activ.EndTime = eTime.Unix()
	this.activ.Update(this.activ)
}
